package com.sjgtw.cloud.system.controller;

import com.sjgtw.cloud.common.core.constant.UserConstants;
import com.sjgtw.cloud.common.core.domain.R;
import com.sjgtw.cloud.common.core.exception.BaseException;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.utils.encrypt.RSAUtils;
import com.sjgtw.cloud.common.core.utils.poi.ExcelUtil;
import com.sjgtw.cloud.common.core.web.controller.BaseController;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.core.web.page.TableDataInfo;
import com.sjgtw.cloud.common.log.annotation.Log;
import com.sjgtw.cloud.common.log.enums.BusinessType;
import com.sjgtw.cloud.common.security.annotation.PreAuthorize;
import com.sjgtw.cloud.system.api.domain.SysDept;
import com.sjgtw.cloud.system.api.domain.SysRole;
import com.sjgtw.cloud.system.api.domain.SysUser;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.system.service.ISysDeptService;
import com.sjgtw.cloud.system.service.ISysPermissionService;
import com.sjgtw.cloud.system.service.ISysPostService;
import com.sjgtw.cloud.system.service.ISysRoleService;
import com.sjgtw.cloud.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>Title: 用户信息管理</p>
 * <p>Description: </p>
 * @author Admin
 * @date 2020-7-7
 */
@Api(value = "用户信息管理",tags = {"用户信息管理接口"}) 
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;
    
    @Autowired
    private ISysDeptService deptService;

    /**
     * <p>Title: 获取用户列表-分页</p>
     * <p>Description: </p>
     * @param user
     * @return
     */
    @ApiOperation("获取用户列表-分页")
    //@PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }
    
    /**
     * <p>Title: 用户数据导出</p>
     * <p>Description: </p>
     * @param response
     * @param user
     * @throws IOException 
     */
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) throws IOException
    {
//        List<SysUser> list = userService.selectUserList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        util.exportExcel(response, list, "用户数据");
    	throw new BaseException("用户数据为敏感数据，不提供数据导出功能！");
    }
    
    /**
     * <p>Title: 用户数据EXCEL导入</p>
     * <p>Description: 针对少量数据，一次不超过500条的数据导入</p>
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize(hasPermi = "system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }
    
    /**
     * <p>Title: EXCEL数据导入模板</p>
     * <p>Description: </p>
     * @param response
     * @throws IOException
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * <p>Title: 通过username获取当前用户信息</p>
     * <p>Description: </p>
     * @param username
     * @return
     */
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误 ！");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * <p>Title: 通过userId获取用户信息</p>
     * <p>Description: </p>
     * @param userId
     * @return
     */
    @GetMapping("/user/{userId}")
    public R<LoginUser> getUser(@PathVariable("userId") Long userId) {
        SysUser sysUser = userService.selectUserById(userId);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误 ！");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * <p>Title: 获取当前用户信息</p>
     * <p>Description: </p>
     * @param username
     * @return
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", userService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * <p>Title: 根据用户ID获取信息</p>
     * <p>Description: </p>
     * @param userId
     * @return
     */
    @ApiOperation("根据用户ID获取信息")
	@ApiImplicitParam(name = "userId", value = "用户ID", required = false, dataType = "Long", paramType = "path")
    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * <p>Title: 新增用户</p>
     * <p>Description: </p>
     * @param user
     * @return
     */
    @ApiOperation("新增用户")
    @PreAuthorize(hasPermi = "system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在！");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在！");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在！");
        }
        //RSA密码解密
        String password = user.getPassword();
        try {
			password = RSAUtils.priKeyDecrypt(password, RSAUtils.priKey, null);
		} catch (Exception e) {
			return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，密码设置不符合规范！");
		}
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(password));
        return toAjax(userService.insertUser(user));
    }

    /**
     * <p>Title: 修改用户</p>
     * <p>Description: </p>
     * @param user
     * @return
     */
    @ApiOperation("修改用户")
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在！");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在！");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * <p>Title: 删除用户</p>
     * <p>Description: </p>
     * @param user
     * @return
     */
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "userIds", value = "用户ID数组集", required = true, allowMultiple=true , dataType = "Long", paramType = "path")
    @PreAuthorize(hasPermi = "system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * <p>Title: 系统管理员重置密码</p>
     * <p>Description: </p>
     * @param user
     * @return
     */
    @ApiOperation("系统管理员重置密码")
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        //RSA密码解密
        String password = user.getPassword();
        try {
			password = RSAUtils.priKeyDecrypt(password, RSAUtils.priKey, null);
		} catch (Exception e) {
			return AjaxResult.error("密码重置失败，请输入正确格式的密码！");
		}
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * <p>Title: 修改用户状态</p>
     * <p>Description: </p>
     * @param user
     * @return
     */
    @ApiOperation("修改用户状态")
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }
    
    /**
     * <p>Title: 用户名密码超过次数 系统锁定用户</p>
     * <p>Description: </p>
     * @param userid  用户ID
     * @return
     */
    @PutMapping("/lockUserStatus")
    public R<Integer> lockUserStatus(@RequestParam("userid") Long userid)
    {
    	SysUser user = new SysUser();
    	user.setUserId(userid);
    	user.setStatus("1");
        //userService.checkUserAllowed(user);
        user.setUpdateBy("lockUserStatus");
        return R.ok(userService.updateUserStatus(user));
    }
    
    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }
    
    /**
     * <p>Title: 用户授权角色</p>
     * <p>Description: </p>
     * @param userId
     * @param roleIds
     * @return
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }
    
    /**
     * <p>Title: deptTree</p>
     * <p>Description: 获取部门树列表</p>
     * @param dept
     * @return
     */
    @PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return AjaxResult.success(deptService.selectDeptTreeList(dept));
    }

}
